define([], function () {
  'use strict'
  function getdefaultConfig () {
    return {
      method: 'get',
      contentType: 'application/json;charset=utf-8',
      // resource:"data"
    }
  }

  function parseUrl (url, params = {}) {
    const idx = url.indexOf('?')
    if (idx < 0) {
      url = url + '?'
    } else if (idx !== url.length - 1) {
      if (url.charAt(url.length - 1) !== '&') {
        url = url + '&'
      }
    }
    for (const key in params) {
      if (Object.prototype.hasOwnProperty.call(params, key)) {
        const v = params[key]
        if (v !== undefined && v !== null) {
          if (
            Object.prototype.toString.call(params[key]) === '[object Array]'
          ) {
            params[key].forEach((item) => {
              url += key + '=' + item + '&'
            })
          } else {
            url += key + '=' + params[key] + '&'
          }
        }
      }
    }
    if (url.endsWith('&') || url.endsWith('?')) {
      url = url.slice(0, -1)
    }
    return url
  }

  function request (config) {
    config = Object.assign({}, getdefaultConfig(), config)
    if (config.data && typeof config.data === 'object') {
      if (!(config.data instanceof FormData)) {
        config.data = JSON.stringify(config.data)
      }
    }
    if (config.params) {
      config.url = parseUrl(config.url, config.params)
      delete config.params
    }
    let r, rej
    const p = new Promise((resolve, reject) => {
      r = resolve
      rej = reject
    })
    const method = config.method
    Reflect.deleteProperty(config, 'method')
    if (method === 'download') {
      $.el[method](config.url)
      return
    }
    $.el[method]({
      ...config,
      success (res) {
        if (res.success === true && res.code === '200') {
          r(res)
        } else {
          r(res)
        }
        // if (config.resource) {
        //   r(res.res?.[config.resource])
        // } else {
        //   r(res.res)
        // }
      },
      error (err) {
        rej(err)
      },
    })
    return p
  }
  return request
})
